package com.tencent.wxpay.demo.service.impl;

import com.tencent.wxpay.WXPay;
import com.tencent.wxpay.common.RandomStringGenerator;
import com.tencent.wxpay.common.Signature;
import com.tencent.wxpay.demo.common.Constants;
import com.tencent.wxpay.demo.listener.ResultListener;
import com.tencent.wxpay.demo.service.UnifiedOrderService;
import com.tencent.wxpay.demo.util.TestUtil;
import com.tencent.wxpay.protocol.model.TradeType;
import com.tencent.wxpay.protocol.request.UnifiedOrderReqData;
import com.tencent.wxpay.protocol.response.UnifiedOrderResData;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UnifiedOrderServiceImpl implements UnifiedOrderService {

    @Override
    public UnifiedOrderResData doUnifiedOrder(String openid, String ip, String notifyUrl) {
        DateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        // 订单号
        String outTradeNo = sf.format(new Date());
        try{
            // TODO 测试数据，每次1分钱
            UnifiedOrderReqData unifiedOrderReqData = new UnifiedOrderReqData(
                    "测试下单",
                    outTradeNo,
                    1,
                    ip,
                    notifyUrl,
                    TradeType.JSAPI,
                    null,
                    openid);
            UnifiedOrderResData unifiedOrderResData = WXPay.doUnifiedOrderBusiness(unifiedOrderReqData,new ResultListener<UnifiedOrderResData>());
            return unifiedOrderResData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map<String, Object> doPaySign(UnifiedOrderResData unifiedOrderResData) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("appId", Constants.APPID);
        map.put("timeStamp", Long.toString(System.currentTimeMillis()));
        map.put("nonceStr", RandomStringGenerator.getRandomStringByLength(32));
        map.put("package", "prepay_id=" + unifiedOrderResData.getPrepay_id());
        map.put("signType", "MD5");
        map.put("paySign", Signature.getSign(map));
        map.remove("appId");
        return map;
    }

    public static void main(String[] args) {
        if(TestUtil.init()){
            try{
                UnifiedOrderService unifiedOrderService = new UnifiedOrderServiceImpl();
                UnifiedOrderResData unifiedOrderResData = unifiedOrderService.doUnifiedOrder("oVlO4wYCySLJ3CNGwTl3I0ToZe98","122.224.86.107","http://www.zcjt400.com/wxpay/unifiedOrder/callback.do");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
